package com.dingwen.treasure.core.controller;

import com.dingwen.treasure.base.constant.RedisConstant;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.base.pojo.vo.ResultGenerator;
import com.dingwen.treasure.common.redis.service.RedisService;
import com.dingwen.treasure.core.annotation.ReSubmit;
import com.dingwen.treasure.core.config.CaptchaProperties;
import com.dingwen.treasure.core.service.CaptchaService;
import com.dingwen.treasure.model.vo.CaptchaVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 　验证码Api // TODO
 * 　@author dingwen
 * 　@date 2022/6/11
 */
@Api(tags = "生成验证码")
@RestController
@Slf4j
@RequestMapping("captcha")
public class CaptchaController {

    /**
     * 验证码服务
     */
    @Resource
    private  CaptchaService captchaService;

    /**
     * redis 服务
     */
    @Resource
    private  RedisService redisService;

    /**
     * 验证码配置
     */
    @Resource
    private  CaptchaProperties captchaProperties;

    /**
     * 生成数字验证码
     *
     * @return {@link Result}
     */
    @ApiOperation("生成随机数字验证码")
    @ReSubmit(message = "频繁申请数字验证码", isDeleteKey = false, time = 1)
    @GetMapping("/number")
    public Result<CaptchaVo> generateNumberCaptcha() {
        // 获取验证码
        CaptchaVo captchaVO = captchaService.generateNumberCaptcha();

        // 将验证码存储到redis (验证码有效期两分钟)
        // key
        String key = RedisConstant.CAPTCHA_KEY.concat(captchaVO.getCodeKey());
        redisService.setCacheObject(key, captchaVO.getCode(),
                captchaProperties.getTime(), captchaProperties.getUnit());

        return ResultGenerator.genSuccessResult(captchaVO);
    }

    /**
     * 生成图像验证码
     *
     * @return {@link Result}<{@link CaptchaVo}>
     * @throws Exception 例外
     */
    @ApiOperation("生成随机图形验证码")
    @ReSubmit(message = "频繁申请图形验证码", isDeleteKey = false, time = 10)
    @GetMapping("/image")
    public Result<CaptchaVo> generateImageCaptcha() {
        // 通过响应流返回
        CaptchaVo captchaVO = captchaService.generateImageCaptcha();
        // 将验证码存储到redis (验证码有效期两分钟)
        // key
        String key = RedisConstant.CAPTCHA_KEY.concat(captchaVO.getCodeKey());

        redisService.setCacheObject(key, captchaVO.getCode(),
                captchaProperties.getTime(), captchaProperties.getUnit());

        return ResultGenerator.genSuccessResult(captchaVO);
    }

}
